package com.glasses.orm.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glasses.orm.base.Ex.BaseEx;
import org.springframework.stereotype.Component;
import wangchao.tools.PostOrGet;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 微信Utils
 * Created by ashin on 2017/8/15.
 */
@Component
public class WxUtils extends BaseEx {

    //微信appId
    private String appId;

    //微信secrect
    private String appSecret;

    //商户号
    private final static String mch_id = "1519396091";

    //设备号
    private final static String device_info = "001";

    //商品描述
    private final static String body = "镇江镜宝配镜服务有限公司";

    //通知地址
    private final static String notify_url = "https://glasses.0511mzone.com/wx/api/payCallback";

    //交易类型
    private final static String trade_type ="JSAPI";

    //微信支付api
    private final static String wxpay_key ="zhangshangpeijingbao012345654321";

    //微信支付url
    private final static String wxpay_url ="https://api.mch.weixin.qq.com/pay/unifiedorder";

    //获得access_token的地址
    private static String getAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

    //授权URL
    private static String oauth_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=STATE#wechat_redirect";

    //获得用户openId地址
    private static String wx_openId_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";

    //获取微信用户信息
    private static String wx_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN";

    //根据access_token获得ticket
    private static String wx_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi";

    //微信发送消息模板接口
    private static String wx_template_send_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s";

    //获取access_token的时间
    private static Date accessTokenTime = new Date();

    //获得tikcet的时间
    private static Date ticketTime = new Date();

    //token 缓存
    private static String accessToken = null;

    //ticket 缓存
    private static String wxTicket = null;

    public static Date getTicketTime() {
        return (Date) ticketTime.clone();
    }

    public static void setTicketTime(Date ticketTime) {
        WxUtils.ticketTime = (Date)ticketTime.clone();
    }

    public static void setWxTicket(String wxTicket) {
        WxUtils.wxTicket = wxTicket;
    }

    public static String getTicket() {
        return wxTicket;
    }

    public static Date getAccessTokenTime() {
        return (Date)accessTokenTime.clone();
    }

    public static void setAccessTokenTime(Date accessTokenTime) {
        WxUtils.accessTokenTime = (Date)accessTokenTime.clone();
    }

    public static void setAccessToken(String accessToken) {
        WxUtils.accessToken = accessToken;
    }

    public static String getToken() {
        return accessToken;
    }

    public WxUtils() {
        appId = getPropertiesParameterString("xcx_appId");
        appSecret = getPropertiesParameterString("xcx_appSecret");
    }

    /**
     * 微信授权页面
     *
     * @param redirectUri
     * @return
     */
    public String redirectWxOauth(String redirectUri) {
        return String.format(oauth_url, appId, redirectUri, "snsapi_userinfo");
    }

    /**
     * 发送微信模板消息
     * @param params 发送参数
     * @return
     * @throws Exception
     */
    public JSONObject sendTemplate(String params) throws Exception{
        JSONObject accessTokenJSON = getAccessToken();
        if (accessTokenJSON.getInteger("code") == eCode)
            return accessTokenJSON;
        else {
            String accessToken = accessTokenJSON.getString("data");
            String result = PostOrGet.sendPost(String.format(wx_template_send_url,accessToken),params,null);
            return this.codeData(JSON.parseObject(result));
        }
    }

    /**
     * 获得微信OpenId
     *
     * @return
     * @throws Exception
     */
    public JSONObject getWxOpenId(String code) throws Exception {
        String url = String.format(wx_openId_url, appId, appSecret, code);
        String openIdStr = PostOrGet.sendGet(url);
        JSONObject openIdJSON = JSON.parseObject(openIdStr);
        if (openIdJSON.getString("errcode") != null) {
            return this.codeData(eCode, openIdJSON.getString("errmsg"));
        } else {
            return openIdJSON;
        }
    }

    public JSONObject getWxTicket() throws Exception {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(getTicketTime());
        calendar.add(Calendar.MINUTE, 90);
        if (getTicket() == null || calendar.compareTo(Calendar.getInstance()) <= 0) {
            JSONObject accessTokenJSON = getAccessToken();
            if (accessTokenJSON.getInteger("code") == eCode)
                return accessTokenJSON;
            else {
                String accessToken = accessTokenJSON.getString("data");
                String ticketStr = PostOrGet.sendGet(String.format(wx_ticket_url, accessToken));
                JSONObject ticketJSON = JSON.parseObject(ticketStr);
                setWxTicket(ticketJSON.getString("ticket"));
                setTicketTime(new Date());
                return this.codeData(sCode, getTicket());
            }
        } else {
            return codeData(sCode, getTicket());
        }
    }

    /**
     * 获得微信用户信息
     *
     * @return
     * @throws Exception
     */
    public JSONObject getWxUserInfo(String code) throws Exception {
        JSONObject openIdJSON = getWxOpenId(code);
        if (openIdJSON.get("code") != null)
            return this.codeData(eCode, openIdJSON.getString("data"));
        else {
            String userInfoStr = PostOrGet.sendGet(String.format(wx_user_info_url, openIdJSON.getString("access_token"), openIdJSON.getString("openid")));
            JSONObject userInfoJSON = JSON.parseObject(userInfoStr);
            if (userInfoJSON.getString("errcode") != null) {
                return this.codeData(eCode, userInfoJSON.getString("errmsg"));
            }
            return this.codeData(sCode, userInfoJSON);
        }
    }

    /**
     * 获得accessToken
     *
     * @return
     * @throws Exception
     */
    public JSONObject getAccessToken() throws Exception {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(getAccessTokenTime());
        calendar.add(Calendar.MINUTE, 90);
        //如果redis里面的accessToken不存在或者上一次获取的accessToken时间小于或者等于当前时间
        if (getToken() == null || calendar.compareTo(Calendar.getInstance()) <= 0) {
            //重新获取accessToken
            String accessTokenStr = PostOrGet.sendGet(String.format(getAccessTokenUrl, appId, appSecret));
            JSONObject accessTokenJSON = JSONObject.parseObject(accessTokenStr);
            String errorcode = accessTokenJSON.getString("errcode");
            if (errorcode == null) {
                setAccessToken(accessTokenJSON.getString("access_token"));
                setAccessTokenTime(new Date());
                return codeData(sCode, getToken());
            } else {
                return codeData(eCode, accessTokenJSON.getString("errmsg"));
            }
        } else {
            return codeData(sCode, getToken());
        }
    }

    public Map<String, String> sign(String url) throws Exception {
        String jsapi_ticket = getWxTicket().getString("data");
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;

        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        ret.put("appId",appId);
        return ret;
    }

    //微信支付数据封装
    public String wxPayConfig(Map map) throws Exception {
        Map<String, String> ret = new HashMap<String, String>();
        ret.put("appid",appId);
        ret.put("mch_id",mch_id);
        ret.put("device_info",device_info);
        ret.put("nonce_str",create_nonce_str().replace("-", ""));
        ret.put("body",body);
        ret.put("out_trade_no",map.get("orderId").toString());
        ret.put("total_fee",map.get("total_fee").toString());
        ret.put("spbill_create_ip",map.get("spbill_create_ip").toString());
        ret.put("notify_url",notify_url);
        ret.put("trade_type",trade_type);
        ret.put("openid",map.get("openId").toString());
        ret.put("sign",WXPayUtil.generateSignature(ret,wxpay_key));
        return WXPayUtil.mapToXml(ret);
    }

    //微信支付
    public JSONObject wxPay(Map map) throws Exception{
        String reqBody = wxPayConfig(map);
        URL httpUrl = new URL(wxpay_url);
        HttpURLConnection httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
//        httpURLConnection.setRequestProperty("Host", "api.mch.weixin.qq.com");
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setConnectTimeout(10*1000);
        httpURLConnection.setReadTimeout(10*1000);
        httpURLConnection.connect();
        OutputStream outputStream = httpURLConnection.getOutputStream();
        outputStream.write(reqBody.getBytes("UTF-8"));

        //获取内容
        InputStream inputStream = httpURLConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        final StringBuffer stringBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuffer.append(line);
        }
        String resp = stringBuffer.toString();
        if (stringBuffer!=null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (inputStream!=null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (outputStream!=null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        Map resultMap = WXPayUtil.xmlToMap(resp);
        if("FAIL".equals(resultMap.get("result_code")))
            return this.codeMess(eCode,resultMap.get("err_code_des").toString());
        else{
            Map signMap = new HashMap();
            //微信支付簽名
            signMap.put("appId",appId);
            signMap.put("timeStamp",String.valueOf(getSecondTimestamp(new Date())));
            signMap.put("nonceStr",create_nonce_str().replace("-", ""));
            signMap.put("package","prepay_id=" + resultMap.get("prepay_id").toString());
            signMap.put("signType","MD5");
            signMap.put("paySign",WXPayUtil.generateSignature(signMap,wxpay_key));
            signMap.put("outTradeNo",map.get("orderId").toString());
            signMap.put("prepayId",resultMap.get("prepay_id").toString());
            return this.codeData(signMap);
        }
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

    /**
     * 获取精确到秒的时间戳
     * @return
     */
    private int getSecondTimestamp(Date date){
        if (null == date) {
            return 0;
        }
        String timestamp = String.valueOf(date.getTime());
        int length = timestamp.length();
        if (length > 3) {
            return Integer.parseInt(timestamp.substring(0,length-3));
        } else {
            return 0;
        }
    }
}
